package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"strings"
)

func LogRequestMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1. 记录请求头
		headers := make(map[string]string)
		for k, v := range c.Request.Header {
			headers[k] = strings.Join(v, ",")
		}

		// 2. 读取请求体并重置（避免后续处理无法获取 Body）
		bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // 关键：恢复 Body

		// 3. 记录日志
		logData := map[string]interface{}{
			"method":    c.Request.Method,
			"path":      c.Request.URL.Path,
			"headers":   headers,
			"body":      string(bodyBytes),
			"client_ip": c.ClientIP(),
		}
		log.Printf("[抖音回调] 请求详情: %+v", logData)

		c.Next()
	}
}
